"use client";
import { useState, useEffect, useCallback } from "react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import CommonSelector from "@/components/CommonSelector";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { format, addDays, addHours } from "date-fns";
import { zhCN } from "date-fns/locale";
import { useToast } from "@/components/ui/use-toast";
import { ToastAction } from "@/components/ui/toast";
import { useSession } from "next-auth/react";
import { formatDateForAPI } from '@/lib/dateUtils'
import {
  ChevronLeft,
  ChevronRight,
  MapPin,
  User,
  Phone,
  Calendar,
  Clock,
  Copy,
  Timer,
  AlertTriangle,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogFooter, AlertDialogTitle, AlertDialogDescription, AlertDialogCancel, AlertDialogAction } from "@/components/ui/alert-dialog";
import { useRouter } from "next/navigation";

export default function CourtBooking({
  lang,
  campuses,
  getCourts,
  getBookableTimeblocks,
  createBookOrder,
  getUserBookOrders,
  cancelBookOrder,
  payOrder,
  currentUser,
}) {
  const { data: session } = useSession();
  const { toast } = useToast();
  const router = useRouter();

  // 解析名称中的排序数字
  const parseNameWithSort = (name) => {
    if (!name || typeof name !== 'string') return { displayName: name || '', sortNumber: 0 };

    const match = name.match(/^(.+)-(\d+)$/);
    if (match) {
      return {
        displayName: match[1],
        sortNumber: parseInt(match[2], 10)
      };
    }
    return {
      displayName: name,
      sortNumber: 0
    };
  };

  // 获取显示名称（去掉-{number}部分）
  const getDisplayName = (name) => {
    return parseNameWithSort(name).displayName;
  };

  // 排序函数 - 数字越大越靠前
  const sortByPriority = (items, nameProperty = 'name') => {
    return [...items].sort((a, b) => {
      const aParsed = parseNameWithSort(a[nameProperty]);
      const bParsed = parseNameWithSort(b[nameProperty]);

      // 先按排序数字降序，再按显示名称升序
      if (aParsed.sortNumber !== bParsed.sortNumber) {
        return bParsed.sortNumber - aParsed.sortNumber;
      }
      return aParsed.displayName.localeCompare(bParsed.displayName, 'zh-CN');
    });
  };

  // 获取排序后的校区列表
  const sortedCampuses = sortByPriority(campuses);

  // 默认选择排序后的第一个校区
  const [selectedCampus, setSelectedCampus] = useState(sortedCampuses[0]?.id || campuses[0]?.id);
  const [courts, setCourts] = useState([]);
  const [selectedCourt, setSelectedCourt] = useState("");
  const [startDate, setStartDate] = useState(new Date());
  const [bookableTimeblocks, setBookableTimeblocks] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedTimeblocks, setSelectedTimeblocks] = useState([]);
  const [userOrders, setUserOrders] = useState([]);
  const [showOrderDialog, setShowOrderDialog] = useState(false);
  const [activeDay, setActiveDay] = useState(0); // 移动端视图中当前激活的日期索引
  const [payLoading, setPayLoading] = useState(false); // 支付中
  const [paySuccess, setPaySuccess] = useState(false); // 支付成功
  const [hasUnpaidOrder, setHasUnpaidOrder] = useState(false); // 是否有未支付订单
  const [showPhoneDialog, setShowPhoneDialog] = useState(false); // 新增：缺少手机号提示

  // 时间段列表
  const timeSlots = [
    "07:00",
    "07:30",
    "08:00",
    "08:30",
    "09:00",
    "09:30",
    "10:00",
    "10:30",
    "11:00",
    "11:30",
    "12:00",
    "12:30",
    "13:00",
    "13:30",
    "14:00",
    "14:30",
    "15:00",
    "15:30",
    "16:00",
    "16:30",
    "17:00",
    "17:30",
    "18:00",
    "18:30",
    "19:00",
    "19:30",
    "20:00",
    "20:30",
    "21:00",
    "21:30",
    "22:00",
    "22:30",
  ];

  // 生成一周的日期
  const days = Array.from({ length: 7 }, (_, i) => {
    const date = addDays(startDate, i);
    return {
      date,
      // 改为中文星期 x
      dayName: format(date, "EEEE", { locale: zhCN }),
      dateString: format(date, "MM/dd"),
    };
  });

  // 获取排序后的场地列表
  const sortedCourts = sortByPriority(courts);

  // 当校区改变时获取球场
  useEffect(() => {
    const fetchCourts = async () => {
      if (!selectedCampus) {
        setCourts([]);
        return;
      }

      try {
        const courtsData = await getCourts({
          branch_campus_id: selectedCampus,
          status: "active",
        });
        setCourts(courtsData);

        // 如果有球场数据，默认选中第一个（按排序后的顺序）
        if (courtsData.length > 0) {
          const sortedCourtsData = sortByPriority(courtsData);
          setSelectedCourt(sortedCourtsData[0].id);
        } else {
          setSelectedCourt("");
        }
      } catch (error) {
        console.error("Failed to fetch courts:", error);
        toast({
          title: "错误",
          description: "获取场地失败",
          variant: "destructive",
        });
      }
    };

    fetchCourts();
  }, [selectedCampus, toast, getCourts]);

  // 获取可预约时间段
  const fetchBookableTimeblocks = useCallback(async () => {
    setIsLoading(true);
    try {
      // 获取一周内的日期范围
      const startTimeFrom = format(startDate, "yyyy-MM-dd");
      const endTimeTo = format(addDays(startDate, 6), "yyyy-MM-dd");

      // 创建开始和结束日期对象
      const startDateObj = new Date(startTimeFrom);
      startDateObj.setHours(0, 0, 0, 0);

      const endDateObj = new Date(endTimeTo);
      endDateObj.setHours(23, 59, 59, 999);

      const timeblocks = await getBookableTimeblocks({
        court_id: selectedCourt,
        start_time_from: formatDateForAPI(startDateObj),
        end_time_to: formatDateForAPI(endDateObj),
        status: "active",
      });
      setBookableTimeblocks(timeblocks);
    } catch (error) {
      console.error("Error fetching bookable timeblocks:", error);
      toast({
        title: "获取可预约时间失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  }, [getBookableTimeblocks, selectedCourt, startDate, toast]);

  // 获取用户订单
  const fetchUserOrders = useCallback(async () => {
    if (!currentUser?.id) return;

    try {
      const orders = await getUserBookOrders({ user_id: currentUser.id });
      console.log("user orders", orders);

      // 按创建时间逆序排列，确保新订单排在前面
      const sortedOrders = [...orders || []].sort((a, b) =>
        new Date(b.created_at) - new Date(a.created_at)
      );

      setUserOrders(sortedOrders);

      // 检查是否存在未支付的订单
      const unpaidOrders = sortedOrders.filter(order =>
        order.status === "active" && !order.is_paid
      );
      setHasUnpaidOrder(unpaidOrders.length > 0);
    } catch (error) {
      console.error("Failed to fetch user orders:", error);
      toast({
        title: "错误",
        description: "获取订单失败",
        variant: "destructive",
      });
    }
  }, [currentUser, toast, getUserBookOrders]);

  useEffect(() => {
    fetchBookableTimeblocks();
    fetchUserOrders();
  }, [fetchBookableTimeblocks, fetchUserOrders]);

  // 检查时间段是否可预约
  const getTimeSlotStatus = (day, timeSlot, courtId) => {
    const dayStr = format(day.date, "yyyy-MM-dd");
    const [hour, minute] = timeSlot.split(":");

    // 使用新的日期格式化函数
    const date = new Date(day.date);
    date.setHours(parseInt(hour), parseInt(minute), 0);
    const startTime = formatDateForAPI(date);

    // 查找该时间段是否存在可预约的时间块
    const timeblock = bookableTimeblocks.find(
      (tb) =>
        tb.court_id === courtId &&
        tb.start_time === startTime &&
        tb.status === "active" &&
        tb.court_book_order_id === null // 确保没有被预约
    );

    if (!timeblock) return { available: false };

    return {
      available: true,
      timeblock: timeblock,
      isSelected: selectedTimeblocks.some((id) => id === timeblock.id),
    };
  };

  // 切换选中状态
  const toggleTimeSlot = (timeblock) => {
    if (!timeblock) return;

    setSelectedTimeblocks((prev) => {
      // 如果已经选中，则取消选择
      if (prev.includes(timeblock.id)) {
        // 检查移除后是否会导致不连续（仅当有2个以上时间段时检查）
        const newSelection = prev.filter(id => id !== timeblock.id);
        if (newSelection.length >= 2) {
          // 确保移除后的时间段仍然连续
          const remainingTimeblocks = bookableTimeblocks.filter(tb =>
            newSelection.includes(tb.id)
          ).sort((a, b) => new Date(a.start_time) - new Date(b.start_time));

          // 检查连续性
          for (let i = 1; i < remainingTimeblocks.length; i++) {
            const prevEndTime = new Date(remainingTimeblocks[i-1].end_time);
            const currStartTime = new Date(remainingTimeblocks[i].start_time);
            if (prevEndTime.getTime() !== currStartTime.getTime()) {
              toast({
                title: "警告",
                description: "移除此时间段会导致选择的时间段不连续",
                duration: 3000,
              });
              return prev; // 不允许移除
            }
          }
        }
        return newSelection;
      } else {
        // 添加新的时间段，需要检查连续性
        if (prev.length === 0) {
          // 如果是第一个选择的时间段，直接添加
          return [...prev, timeblock.id];
        }

        // 获取当前所有选中的时间块
        const currentSelectedTimeblocks = bookableTimeblocks
          .filter(tb => prev.includes(tb.id))
          .sort((a, b) => new Date(a.start_time) - new Date(b.start_time));

        // 获取新的时间块
        const newTimeblock = timeblock;
        const newStartTime = new Date(newTimeblock.start_time);
        const newEndTime = new Date(newTimeblock.end_time);

        // 检查是否与当前选择的时间段连续
        const earliestSelected = currentSelectedTimeblocks[0];
        const latestSelected = currentSelectedTimeblocks[currentSelectedTimeblocks.length - 1];

        const earliestStartTime = new Date(earliestSelected.start_time);
        const latestEndTime = new Date(latestSelected.end_time);

        // 判断新时间段是否与当前选择的时间段连续
        if (newEndTime.getTime() === earliestStartTime.getTime() ||
            newStartTime.getTime() === latestEndTime.getTime()) {
          return [...prev, timeblock.id];
        } else {
          // 检查是否在已选择的时间段内
          const isInBetween = currentSelectedTimeblocks.some((tb, index) => {
            if (index === currentSelectedTimeblocks.length - 1) return false;

            const currEndTime = new Date(tb.end_time);
            const nextStartTime = new Date(currentSelectedTimeblocks[index + 1].start_time);

            return newStartTime.getTime() === currEndTime.getTime() &&
                   newEndTime.getTime() === nextStartTime.getTime();
          });

          if (isInBetween) {
            return [...prev, timeblock.id];
          }

          toast({
            title: "提示",
            description: "请选择连续的时间段",
            duration: 3000,
          });
          return prev; // 不连续，不添加
        }
      }
    });
  };

  // 前一周/后一周
  const goToPreviousWeek = () => {
    setStartDate((prev) => addDays(prev, -7));
    setActiveDay(0);
  };

  const goToNextWeek = () => {
    setStartDate((prev) => addDays(prev, 7));
    setActiveDay(0);
  };

  // 创建预约订单
  const createOrder = async () => {
    if (!currentUser?.id) {
      toast({
        title: "提示",
        description: "请先登录",
        variant: "destructive",
      });
      return;
    }

    if (hasUnpaidOrder) {
      toast({
        title: "提示",
        description: "您有未支付的订单，请先完成支付",
        variant: "destructive",
        action: (
          <ToastAction altText="查看订单" onClick={() => setShowOrderDialog(true)}>
            查看订单
          </ToastAction>
        )
      });
      return;
    }

    if (selectedTimeblocks.length === 0) {
      toast({
        title: "提示",
        description: "请选择要预约的时间段",
        variant: "destructive",
      });
      return;
    }

    // 检查是否选择了过去的时间段
    if (checkHasPastTimeSlots()) {
      toast({
        title: "无法预约",
        description: "不能预约过去的时间段，请重新选择",
        variant: "destructive",
      });
      return;
    }

    console.log("session?.user", session?.user);

    if (!currentUser?.phone_number) {
      setShowPhoneDialog(true);
      return;
    }

    setIsLoading(true);
    try {
      // 获取所选时间块
      const selectedBlocks = bookableTimeblocks.filter((tb) =>
        selectedTimeblocks.includes(tb.id)
      );

      if (selectedBlocks.length === 0) {
        toast({
          title: "错误",
          description: "没有选择有效的时间段",
          variant: "destructive",
        });
        return;
      }

      // 找出所选时间段的最早和最晚时间
      const startTime = selectedBlocks.reduce(
        (earliest, tb) => (tb.start_time < earliest ? tb.start_time : earliest),
        selectedBlocks[0].start_time
      );

      const endTime = selectedBlocks.reduce(
        (latest, tb) => (tb.end_time > latest ? tb.end_time : latest),
        selectedBlocks[0].end_time
      );

      // 创建订单
      await createBookOrder({
        court_id: selectedCourt,
        user_id: currentUser?.id,
        start_time: startTime,
        end_time: endTime,
        status: "active",
        timeblock_ids: selectedTimeblocks,
      });

      toast({
        title: "成功",
        type: "foreground",
        duration: 2000,
        description: "预约已成功创建，请在 15 分钟内支付",
      });
      setShowOrderDialog(true);
      // 刷新数据
      setSelectedTimeblocks([]);
      fetchBookableTimeblocks();
      fetchUserOrders();
    } catch (error) {
      console.error("Failed to create order:", error);
      toast({
        title: "错误",
        description: "创建预约失败",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 取消预约
  const cancelOrder = async (orderId) => {
    if (!confirm("确定要取消预约吗？")) return;

    setIsLoading(true);
    try {
      await cancelBookOrder(orderId);

      toast({
        title: "成功",
        description: "预约已取消",
      });

      // 刷新数据
      await fetchUserOrders(); // 等待获取最新订单完成
      fetchBookableTimeblocks();

      // 检查取消后是否还有其他未支付订单
      const remainingUnpaidOrders = userOrders.filter(
        order => order.id !== orderId && order.status === "active" && !order.is_paid
      );
      setHasUnpaidOrder(remainingUnpaidOrders.length > 0);

      // 如果没有未支付订单，关闭预约对话框
      if (remainingUnpaidOrders.length === 0) {
        setShowOrderDialog(false);
      }
    } catch (error) {
      console.error("Failed to cancel order:", error);
      toast({
        title: "错误",
        description: "取消预约失败",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 找到当前选中场地的名称（显示名称）
  const selectedCourtName = courts.find((c) => c.id === selectedCourt)?.name
    ? getDisplayName(courts.find((c) => c.id === selectedCourt).name)
    : "";

  // 获取当前选中场地的完整信息
  const selectedCourtInfo = courts.find((c) => c.id === selectedCourt);

  // 判断memo是否为https链接
  const isHttpsLink = (url) => {
    if (!url || typeof url !== 'string') return false;
    return url.trim().toLowerCase().startsWith('https://');
  };

  // 获取场地介绍链接
  const getCourtIntroLink = () => {
    if (selectedCourtInfo && isHttpsLink(selectedCourtInfo.memo)) {
      return selectedCourtInfo.memo;
    }
    return "https://docs.qq.com/doc/p/7e6f59ac5d5deb3a9ea8f843c7f526915a3e55fd?nlc=1";
  };

  // 获取场地介绍文本
  const getCourtIntroText = () => {
    const prefix = selectedCourtName ? `${selectedCourtName} ` : '';
    return `${prefix}场地介绍指引`;
  };

  // 前一天/后一天（移动端视图）
  const goToPreviousDay = () => {
    if (activeDay > 0) {
      setActiveDay(activeDay - 1);
    }
  };

  const goToNextDay = () => {
    if (activeDay < 6) {
      setActiveDay(activeDay + 1);
    }
  };

  // 获取校区信息
  const getCourtCampusInfo = useCallback(
    async (courtId) => {
      if (!courtId || !courts.length) return null;

      // 找到对应的场地
      const court = courts.find((c) => c.id === courtId);
      if (!court) return null;

      // 获取对应的校区信息
      try {
        // 假设有一个API来获取校区信息
        const campusInfo = campuses.find(
          (c) => c.id === court.branch_campus_id
        );
        return campusInfo;
      } catch (error) {
        console.error("Failed to fetch campus info:", error);
        return null;
      }
    },
    [courts, campuses]
  );

  // 定义一个函数用于打开地图导航
  const openMapNavigation = (address) => {
    // 微信环境中，可以使用微信JSSDK或直接跳转到地图应用
    // 这里使用简单的URL方案，实际使用可能需要根据微信API调整
    const encodedAddress = encodeURIComponent(address);
    window.location.href = `https://apis.map.qq.com/uri/v1/geocoder?coord=&address=${encodedAddress}`;
  };

  // 添加复制地址功能
  const copyAddressToClipboard = (address) => {
    if (!address) return;

    navigator.clipboard
      .writeText(address)
      .then(() => {
        toast({
          title: "已复制",
          description: "地址已复制到剪贴板，打开手机地图导航吧",
          duration: 2000,
        });
      })
      .catch((err) => {
        console.error("无法复制地址: ", err);
        toast({
          title: "复制失败",
          description: "请手动长按地址进行复制",
          variant: "destructive",
          duration: 3000,
        });
      });
  };

  const launchWechatPay = async (order, court, timeStr) => {
    setPayLoading(true);
    try {
      console.log('current user',session.user);
      const res = await payOrder({
        openid: session.user.openid,
        orderId: order.out_trade_no,
        userName: session?.user?.name,
        courtName: court?.name,
        startTime: timeStr,
        price: order.timeblocks
          ? order.timeblocks.reduce((sum, tb) => sum + tb.price, 0)
          : 0,
      });
      console.log("res", res);
      //launch the wechat pay page
      invokeWeChatPay(res);
    } catch (error) {
      setPayLoading(false);
      console.error("Failed to launch wechat pay:", error);
      toast({
        title: "错误",
        description: "拉起支付失败，请稍后重试",
        variant: "destructive",
        duration: 3000,
      });
    }
  }

  const invokeWeChatPay = (params) => {
    console.log("invokeWeChatPay", params);
    console.log("window.WeixinJSBridge", window.WeixinJSBridge);
    if (window.WeixinJSBridge) {
      callWeChatPay(params);
    } else {
      document.addEventListener(
        "WeixinJSBridgeReady",
        () => callWeChatPay(params),
        false
      );
    }
  };

  const callWeChatPay = (params) => {
    console.log("params", params);
    window.WeixinJSBridge.invoke(
      "getBrandWCPayRequest",
      {
        appId: params.appId,
        timeStamp: `${params.timeStamp}`,
        nonceStr: params.nonceStr,
        package: params.package,
        signType: params.signType,
        paySign: params.paySign,
      },
      function (res) {
        setPayLoading(false);
        if (res.err_msg === "get_brand_wcpay_request:ok") {
          setPaySuccess(true);
          //toast 用户已经支付成功
          toast({
            title: "成功",
            description: "支付成功",
            duration: 2000,
          });
          fetchUserOrders();//重新获取订单状态
          setHasUnpaidOrder(false); // 支付成功后清除未支付订单标志
        } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
          alert("您已取消支付。");
        } else {
          alert("支付失败，请稍后重试。");
        }
      }
    );
  };

  // 在现有函数后面添加检查过去时间的函数
  const checkHasPastTimeSlots = () => {
    if (selectedTimeblocks.length === 0) return false;

    const now = new Date();
    const selectedBlocks = bookableTimeblocks.filter((tb) =>
      selectedTimeblocks.includes(tb.id)
    );

    return selectedBlocks.some(block => new Date(block.start_time) < now);
  };

  return (
    <div className="space-y-6 w-full">
      <div className="flex flex-row justify-between items-center">
        <Button
          onClick={() => {
            fetchUserOrders();
            setShowOrderDialog(true);
          }}
          className={hasUnpaidOrder ? "relative" : ""}
        >
          {hasUnpaidOrder && (
            <span className="absolute -top-1 -right-1 flex h-3 w-3">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
              <span className="relative inline-flex rounded-full h-3 w-3 bg-red-500"></span>
            </span>
          )}
          我的预约
        </Button>
        <div className="text-sm font-bold text-gray-500 animate-bounce">
        <span className="text-2xl">👉</span>
        <a
          href={getCourtIntroLink()}
          className="text-primary"
        >
          {getCourtIntroText()}
        </a>
      </div>
      </div>

      {hasUnpaidOrder && (
        <div className="bg-amber-50 border border-amber-200 rounded-md p-3 flex items-center gap-2 text-amber-800 shadow-sm">
          <AlertTriangle className="h-5 w-5 text-amber-500 flex-shrink-0" />
          <div className="flex-1">
            <p className="font-medium">您有未支付的订单</p>
            <p className="text-sm">请先支付后再进行新的预约</p>
          </div>
          <Button
            variant="outline"
            className="border-amber-300 hover:bg-amber-100 hover:text-amber-900"
            onClick={() => setShowOrderDialog(true)}
          >
            去支付
          </Button>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
        <Card className="overflow-hidden">
          <CardContent className="p-2 pt-3">
            <div className="text-xs font-medium mb-1.5 text-muted-foreground">选择校区</div>
            <div className="w-full">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-1.5">
                {sortedCampuses.map((campus) => (
                  <button
                    key={campus.id}
                    onClick={() => setSelectedCampus(campus.id)}
                    className={cn(
                      "px-3 py-1.5 text-xs rounded-md transition-colors text-center",
                      selectedCampus === campus.id
                        ? "bg-primary text-primary-foreground"
                        : "bg-muted hover:bg-muted/80 text-muted-foreground"
                    )}
                  >
                    {getDisplayName(campus.name)}
                  </button>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="overflow-hidden">
          <CardContent className="p-2 pt-3">
            <div className="text-xs font-medium mb-1.5 text-muted-foreground">选择场地</div>
            <div className="w-full">
              <div className="grid grid-cols-3 md:grid-cols-5 gap-1.5">
                {sortedCourts.map((court) => (
                  <button
                    key={court.id}
                    onClick={() => setSelectedCourt(court.id)}
                    disabled={courts.length === 0}
                    className={cn(
                      "px-3 py-1.5 text-xs rounded-md transition-colors text-center",
                      selectedCourt === court.id
                        ? "bg-primary text-primary-foreground"
                        : "bg-muted hover:bg-muted/80 text-muted-foreground",
                      "disabled:opacity-50 disabled:pointer-events-none"
                    )}
                  >
                    {getDisplayName(court.name)}
                  </button>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {selectedCourt && (
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-sm font-bold">
              {selectedCourtName}
            </CardTitle>
            <div className="space-x-2 items-center">
              <Button
                onClick={goToPreviousWeek}
                variant="outline"
                size="sm"
                className="hidden md:inline-flex"
              >
                上一周
              </Button>
              <Button
                onClick={goToNextWeek}
                variant="outline"
                size="sm"
                className="hidden md:inline-flex"
              >
                下一周
              </Button>

              {/* 移动端周选择器 */}
              <div className="flex items-center md:hidden">
                <Button
                  onClick={goToPreviousWeek}
                  variant="outline"
                  size="icon"
                  className="h-8 w-14"
                >
                  上一周
                </Button>
                <span className="mx-2 text-sm">
                  {format(startDate, "MM月dd")}
                </span>
                <Button
                  onClick={goToNextWeek}
                  variant="outline"
                  size="icon"
                  className="h-8 w-14"
                >
                  下一周
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex justify-center py-8">加载中...</div>
            ) : (
              <>
                {/* 桌面版视图 - 完整表格 */}
                <div className="hidden md:block overflow-x-auto">
                  <table className="w-full border-collapse">
                    <thead>
                      <tr>
                        <th className="border p-2">时间</th>
                        {days.map((day, idx) => (
                          <th key={idx} className="border p-2">
                            {day.dateString}
                            <br />
                            {day.dayName}
                          </th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {timeSlots.map((timeSlot, idx) => (
                        <tr key={idx}>
                          <td className="border p-2">{timeSlot}</td>
                          {days.map((day, dayIdx) => {
                            const status = getTimeSlotStatus(
                              day,
                              timeSlot,
                              selectedCourt
                            );
                            return (
                              <td
                                key={dayIdx}
                                className={`border p-1 text-center text-xs ${
                                  status.available
                                    ? status.isSelected
                                      ? "bg-green-500 text-white cursor-pointer hover:bg-green-600 border-green-600 shadow-sm"
                                      : "bg-blue-50 border-blue-200 cursor-pointer hover:bg-blue-100 text-blue-900"
                                    : "bg-gray-100 text-gray-400"
                                }`}
                                onClick={() => {
                                  if (status.available) {
                                    toggleTimeSlot(status.timeblock);
                                  }
                                }}
                              >
                                {status.available
                                  ? status.isSelected
                                    ? "已选择"
                                    : `¥${status.timeblock.price}`
                                  : <span className="text-gray-400">不可用</span>}
                              </td>
                            );
                          })}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 移动端视图 - 标签式单天视图 */}
                <div className="md:hidden pb-10">
                  <div className="flex items-center justify-between mb-4">
                    <Button
                      onClick={goToPreviousDay}
                      variant="outline"
                      size="sm"
                      disabled={activeDay === 0}
                    >
                      <ChevronLeft className="h-4 w-4" />
                    </Button>
                    <div className="text-center">
                      <div className="font-medium">
                        {days[activeDay].dateString}
                      </div>
                      <div className="text-sm text-muted-foreground">
                        {days[activeDay].dayName}
                      </div>
                    </div>
                    <Button
                      onClick={goToNextDay}
                      variant="outline"
                      size="sm"
                      disabled={activeDay === 6}
                    >
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                  </div>

                  <div className="grid grid-cols-2 gap-2 pb-24">
                    {timeSlots.map((timeSlot, idx) => {
                      const status = getTimeSlotStatus(
                        days[activeDay],
                        timeSlot,
                        selectedCourt
                      );
                      return (
                        <div
                          key={idx}
                          className={`p-1 rounded border text-center ${
                            status.available
                              ? status.isSelected
                                ? "bg-green-500 border-green-600 text-white shadow-md"
                                : "bg-blue-50 border-blue-200 hover:bg-blue-100 text-blue-900"
                              : "bg-gray-100 border-gray-300 opacity-60"
                          }`}
                          onClick={() => {
                            if (status.available) {
                              toggleTimeSlot(status.timeblock);
                            }
                          }}
                        >
                          {/* if timeSlot is 07:00 ，then show 07:00-07:30, if timeSlot is 07:30, then show 07:30-08:00 */}
                          <div className="text-xs">
                            {timeSlot}-
                            {timeSlot.split(":")[1] === "00"
                              ? `${parseInt(timeSlot.split(":")[0])}:30`
                              : `${parseInt(timeSlot.split(":")[0]) + 1}:00`}
                          </div>
                          {status.available ? (
                            <div
                              className={status.isSelected ? "font-bold text-xs text-white" : "text-xs"}
                            >
                              {status.isSelected
                                ? "已选择"
                                : `¥${status.timeblock.price}`}
                            </div>
                          ) : (
                            <div className="text-gray-400 text-xs">不可用</div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>

                {selectedTimeblocks.length > 0 && (
                  <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 md:relative md:mt-6 md:border md:rounded-md md:bg-gray-50 md:shadow-none shadow-lg z-10">
                    {/* 过去时间提醒 */}

                    <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                      <div>
                        <p className="font-medium">
                          已选择 {selectedTimeblocks.length} 个时间段
                        </p>
                        <p className="text-lg font-bold">
                          总价: ¥
                          {bookableTimeblocks
                            .filter((tb) =>
                              selectedTimeblocks.includes(tb.id)
                            )
                            .reduce((sum, tb) => sum + tb.price, 0)}
                        </p>
                      </div>
                      <Button
                        onClick={createOrder}
                        disabled={isLoading || hasUnpaidOrder || checkHasPastTimeSlots()}
                        className={`w-full md:w-auto ${hasUnpaidOrder ? "bg-gray-400 cursor-not-allowed" : ""}`}
                      >
                        {hasUnpaidOrder ? "请先支付未完成订单" : "确认预约"}
                      </Button>
                    </div>
                  </div>
                )}
              </>
            )}
          </CardContent>
        </Card>
      )}

      {/* 我的预约对话框 */}
      <Dialog open={showOrderDialog} onOpenChange={setShowOrderDialog}>
        <DialogContent className="max-w-lg w-[95vw] md:max-w-3xl rounded-lg">
          <DialogHeader>
            <DialogTitle className="text-xl font-bold">我的预约</DialogTitle>
          </DialogHeader>

          {userOrders.length > 0 ? (
            <div className="space-y-4 max-h-[70vh] overflow-y-auto pb-2">
              {userOrders.map((order) => {
                // 获取场地信息
                const court = courts.find((c) => c.id === order.court_id);
                // 获取场地所属的校区信息
                const campus = campuses.find(
                  (c) => court && c.id === court.branch_campus_id
                );

                // 格式化日期时间
                const startTime = new Date(order.start_time);
                const endTime = new Date(order.end_time);
                const dateStr = startTime.toLocaleDateString("zh-CN", {
                  year: "numeric",
                  month: "long",
                  day: "numeric",
                  weekday: "long",
                });
                const timeStr = `${startTime.toLocaleTimeString("zh-CN", {
                  hour: "2-digit",
                  minute: "2-digit",
                })} - ${endTime.toLocaleTimeString("zh-CN", {
                  hour: "2-digit",
                  minute: "2-digit",
                })}`;

                return (
                  <Card
                    key={order.id}
                    className="overflow-hidden border-0 shadow-md"
                  >
                    <div
                      className={`h-2 ${
                        order.status === "active"
                          ? "bg-green-500"
                          : "bg-gray-400"
                      }`}
                    ></div>
                    <CardContent className="p-0">
                      {/* 订单状态栏 */}
                      <div className="flex justify-between items-center p-3 bg-gray-50">
                        <div className="flex items-center">
                          <Calendar className="h-4 w-4 mr-2 text-gray-500" />
                          <span className="text-sm font-medium">
                            {dateStr}
                          </span>
                        </div>
                        <span
                          className={`px-3 py-1 rounded-full text-sm font-medium ${
                            order.is_paid
                              ? "bg-green-100 text-green-800"
                              : "bg-yellow-100 text-yellow-800"
                          }`}
                        >
                          {order.is_paid ? "已支付" : "待支付"}
                        </span>
                      </div>

                      {/* 主要内容 */}
                      <div className="p-4">
                        {/* 场地和时间信息 */}
                        <div className="mb-4">
                          <h3 className="text-lg font-bold mb-1">
                            {court?.name || "未知场地"}
                          </h3>
                          <div className="flex items-center text-gray-600 mb-1">
                            <Clock className="h-4 w-4 mr-2" />
                            <span>{timeStr}</span>
                          </div>
                          <div className="text-right">
                            <span className="text-lg font-bold text-orange-600">
                              ¥
                              {order.timeblocks
                                ? order.timeblocks.reduce(
                                    (sum, tb) => sum + tb.price,
                                    0
                                  )
                                : 0}
                            </span>
                          </div>
                        </div>

                        {/* 校区信息部分 */}
                        {campus && (
                          <div className="mt-4 pt-4 border-t border-gray-100">
                            <h4 className="font-medium mb-2 text-gray-700">
                              校区信息
                            </h4>

                            <div className="space-y-2">
                              <div className="flex items-start">
                                <MapPin className="h-5 w-5 mr-2 text-gray-500 mt-0.5 flex-shrink-0" />
                                <div className="flex-1">
                                  <div
                                    className="text-blue-600 flex items-center mb-1"
                                    onClick={() =>
                                      campus.address &&
                                      openMapNavigation(campus.address)
                                    }
                                  >
                                    <span className="underline">
                                      {campus.address || "地址未提供"}
                                    </span>
                                    <ChevronRight className="h-4 w-4 ml-1" />
                                  </div>
                                  <div className="flex items-center justify-between">
                                    <div className="text-xs text-gray-500">
                                      点击导航至校区
                                    </div>
                                    {campus.address && (
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        className="h-7 px-2 text-xs flex items-center text-blue-600"
                                        onClick={(e) => {
                                          e.stopPropagation();
                                          copyAddressToClipboard(
                                            campus.address
                                          );
                                        }}
                                      >
                                        <Copy className="h-3.5 w-3.5 mr-1" />
                                        复制地址
                                      </Button>
                                    )}
                                  </div>
                                </div>
                              </div>

                              <div className="flex items-center">
                                <User className="h-5 w-5 mr-2 text-gray-500 flex-shrink-0" />
                                <span className="text-gray-700">
                                  {campus.principal || "未设置"}
                                </span>
                              </div>

                              {campus.phone_number && (
                                <div className="flex items-center">
                                  <Phone className="h-5 w-5 mr-2 text-gray-500 flex-shrink-0" />
                                  <a
                                    href={`tel:${campus.phone_number}`}
                                    className="text-blue-600"
                                  >
                                    {campus.phone_number}
                                  </a>
                                </div>
                              )}
                            </div>
                          </div>
                        )}
                      </div>

                      {/* 操作按钮 */}
                      {order.status === "active" && !order.is_paid && (
                        <>
                          <div className="px-4 pb-2">
                            <div className="flex flex-col gap-2 bg-amber-50 border border-amber-200 rounded-md p-2 text-amber-700 text-sm">
                              <div className="flex items-center">
                                <AlertTriangle className="h-4 w-4 mr-2 text-amber-500" />
                                <span>订单将在 <span className="font-bold">15分钟</span> 内自动关闭，请尽快完成支付</span>
                              </div>
                              <div className="flex items-center ml-6">
                                <span>退费须知：开场<span className="font-bold">8小时前</span>可全额退款，<span className="font-bold">4小时前</span>退款50%，<span className="font-bold">4小时内</span>不退。<span className="font-bold">退款</span>请联系前台客服办理</span>
                              </div>
                              <div className="flex items-center ml-6">
                                <span><span className="font-bold">禁止外部教学</span>：教学请联系客服助理 ，违规者将被拒绝入场并不予退款</span>
                              </div>
                            </div>
                          </div>
                          <div className="px-4 pb-4 flex justify-end gap-4">
                            <Button
                              variant="ghost"
                              size="sm"
                              className="rounded-full px-4"
                              onClick={() => cancelOrder(order.id)}
                              disabled={payLoading}
                            >
                              取消预约
                            </Button>
                            <Button
                              variant="destructive"
                              size="sm"
                              className="rounded-full px-4"
                              onClick={() =>
                                launchWechatPay(order, court, timeStr)
                              }
                              disabled={payLoading}
                            >
                              {payLoading ? (
                                <>
                                  <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                  </svg>
                                  处理中...
                                </>
                              ) : (
                                "立即支付"
                              )}
                            </Button>
                          </div>
                        </>
                      )}
                      {order.is_paid && (
                        <div className="px-4 pb-4 flex justify-end gap-4">
                          <p className="text-gray-500">
                            请按时前往，祝您训练愉快！如有疑问，请联系客服。
                          </p>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          ) : (
            <div className="py-12 text-center">
              <div className="inline-block p-4 bg-gray-100 rounded-full mb-4">
                <Calendar className="h-8 w-8 text-gray-400" />
              </div>
              <p className="text-gray-500">暂无预约记录</p>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 缺少手机号警告对话框 */}
      <AlertDialog open={showPhoneDialog} onOpenChange={setShowPhoneDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>请完善手机号</AlertDialogTitle>
            <AlertDialogDescription>
              为了确保我们能够及时联系到您并保障预约权益，请先前往个人中心补充手机号码，再进行定场操作。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>稍后再说</AlertDialogCancel>
            <AlertDialogAction onClick={() => router.push(`/${lang}/profile?redirect=court-booking`)}>
              去完善手机号
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};
